package rpc.intf.impl.serializer;

import com.google.gson.*;
import com.google.gson.JsonSerializer;
import rpc.common.enumeraion.SerializerCode;
import rpc.intf.CommonSerializer;

import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

/**
 * gson序列化器
 */
public class GsonSerializer implements CommonSerializer {
    @Override
    public byte[] serialize(Object obj) {
        Gson gson = new GsonBuilder().registerTypeAdapter(Class.class, new ClassCodec()).create();
        String json = gson.toJson(obj);
        return json.getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public Object deserialize(byte[] bytes, Class<?> clazz) {
        Gson gson = new GsonBuilder().registerTypeAdapter(Class.class, new ClassCodec()).create();

        String json = new String(bytes, StandardCharsets.UTF_8);
        return gson.fromJson(json, clazz);
    }

    /**
     * 解决Gson报错问题 还有其他问题，类型不支持吗？
     */
    private static class ClassCodec implements JsonSerializer<Class<?>>, JsonDeserializer<Class<?>> {

        @Override
        public Class<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            try {
                String str = json.getAsString();
                return Class.forName(str);
            } catch (ClassNotFoundException e) {
                throw new JsonParseException(e);
            }
        }

        @Override
        public JsonElement serialize(Class<?> src, Type typeOfSrc, JsonSerializationContext context) {
            //class -> json
            return new JsonPrimitive(src.getName());
        }
    }
}
